import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreatePermissionDto, DeletePermissionDto, FindManyPermissionDto, UpdatePermissionDto } from '../dto/permission.dto';
import { PrismaService } from 'src/module/prisma/prisma.service';

@Injectable()
export class PermissionService {
    constructor(private readonly prismaService: PrismaService) { }

    async create(cd: CreatePermissionDto) {
        const permission = await this.prismaService.permission.findUnique({
            where: { code: cd.code }
        })
        if (permission) {
            throw new HttpException('权限已存在', HttpStatus.BAD_REQUEST);
        }
        try {
            return this.prismaService.permission.create({ data: { code: cd.code, description: cd.description } })
        } catch (error) {
            throw new HttpException('权限添加失败', HttpStatus.BAD_REQUEST);
        }
    }

    delete(dd: DeletePermissionDto) {
        try {
            return this.prismaService.permission.delete({ where: { id: dd.id } })
        } catch (error) {
            throw new HttpException('权限删除失败', HttpStatus.BAD_REQUEST);
        }
    }

    async update(ud: UpdatePermissionDto) {
        const exist = await this.prismaService.permission.findFirst({
            where: {
                code: ud.code,
                NOT: { id: ud.id }
            }
        });
        if (exist) {
            throw new HttpException('权限已存在', HttpStatus.BAD_REQUEST);
        }
        try {
            return this.prismaService.permission.update({
                where: { id: ud.id },
                data: { code: ud.code, description: ud.description }
            })
        } catch (error) {
            throw new HttpException('权限编辑失败', HttpStatus.BAD_REQUEST);
        }
    }

    async findMany(fmd: FindManyPermissionDto) {
        const res = await this.prismaService.permission.findMany({
            
            skip: fmd.page ? ((fmd.page - 1) * fmd.limit) : 0,
            take: fmd.limit,
            orderBy: { [fmd.orderBy]: fmd.orderDirection },
        });
        return res;
    }
}
